package com.hypo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hypo.mapper.CategoryMapper;
import com.hypo.pojo.Category;
import com.hypo.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    private final CategoryMapper categoryMapper;

    @Override
    public Object find(List<Category> all) {
        List<Category> parents = all.stream().filter(a -> a.getParentId() == 0).toList();
        List<Category> children = all.stream().filter(a -> a.getParentId() > 0).toList();

        parents.forEach(p -> findChildren(p, children));
        return parents;

    }

    private void findChildren(Category p, List<Category> children) {
        List<Category> list = children.stream().filter(c -> Objects.equals(c.getParentId(), p.getId())).toList();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(l -> findChildren(l, children));
        }
        p.setChildren(list);
    }
}
